﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Reflection;
using System.Windows.Media.Imaging;
using FinPlusCommon;
using log = Logger.Logger;
using u = FinPlusUtility.Utility;

namespace FinPlusWPFControls
{
    public sealed class FinPlusMenuItem:FinPlusControl
    {
        public enum Action { Edit, Clone, Copy, Print, None, Default }
        public MenuItem MenuItem { get; private set; }

        private object _placement;
        private readonly string _parms, _childPath, _action;
        private FinPlusWindow _window;
        private static ResourceDictionary _images;

        //construct
        public FinPlusMenuItem(string header, string icon, string action, string parms ="", IFinPlusComp[] menuItems = null)
        {
            MenuItem = new MenuItem();
            if (!header.Equals(""))
                MenuItem.Header = header;
            MenuItem.Click += MenuItem_Click;
            AddIcon(icon);
            _parms = parms;
            _action = action;
            _childPath = u.GetAssemblyPath(Assembly.GetExecutingAssembly()) + "FinPlusSubViews\\";

            if(menuItems != null)
                foreach(FinPlusMenuItem menuItem in menuItems)
                    MenuItem.Items.Add(menuItem.MenuItem);

            IsValid = true;
        }
   
        //common control interface 
        public override void CmdExecute(IFunction command)
        {
            try
            {
                CmdCapture(command);

                switch ((Cmds)Enum.Parse(typeof(Cmds), command.Name, true))
                {
                    case Cmds.ExecuteAction: ExecuteAction(); break;
                    default: throw new Exception(string.Format("event not recognised {0}", command.Name));
                }
            }
            catch (CmdExecuteException e)
            {
                IsValid = log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }
        }

        //private
        private void ExecuteAction()
        {
            //TODO nast rethink
            if (_placement == null) _placement = GetPlacementTarget();

            if(_window == null) _window = ControlSearch.FindVisualParent<FinPlusWindow>((DataGrid)_placement);

            switch (u.EnumParse<Action>(_action, Action.Default))
            {
                case Action.Clone: FinPlusWindow.OpenEditor(GetFunc().Clone(-1), "FuncEdit", Env); break;
                case Action.Edit: FinPlusWindow.OpenEditor(GetFunc(), "FuncEdit", Env); break;
                case Action.Copy: ApplicationCommands.Copy.Execute(null, (DataGrid)_placement); break;
                case Action.Print: new PrintDialog().PrintVisual((DataGrid)_placement, "Printing"); break;
                case Action.None: break;
                case Action.Default: OpenProcess(); break;
            }
        }

        private object GetPlacementTarget()
        {
           var res = MenuItem.Parent;
           do
           {
               //TODO nasty rethink
               if (res.GetType().Equals(typeof(MenuItem)))
                   res = ((MenuItem)res).Parent;
               else
               {
                   if (u.IsTypeOf<ContextMenu>(res.GetType()))
                       return ((ContextMenu)res).PlacementTarget;
                   return ((Menu)res).Parent;
               }

           }
           while(true);
        }

        private IFunction GetFunc()
        {
            return ((IFinPlusFuncDynamic)((DataGrid)_placement).CurrentItem).ToFunction();
        }

        private void AddIcon(string icon)
        {
            if (_images == null)
                _images = new ResourceDictionary { Source = new Uri("pack://application:,,,/FinPlusWPFControls;component/Resource.Images.xaml", UriKind.RelativeOrAbsolute) };

            if (!string.IsNullOrEmpty(icon))
                MenuItem.Icon =  new Image { Source = (BitmapImage)_images[icon] };
        }

        private void OpenProcess()
        {
            FinPlusWindow.OpenWindow(string.Format("{0}{1}", _childPath, _action), _action, _window.Guid, GetFunc().Replace(_parms));
        }

        //cmds
        private enum Cmds { ExecuteAction }

        //events
        private void MenuItem_Click(object s, System.Windows.RoutedEventArgs a) {CmdRouter(Cmds.ExecuteAction.ToString());}
    }
}


























































































//Copyright2013<jnrton>AllRightsReserved 
//Contact j.nrton@finpus